/**
 * 拦截器管理器实现
 */

import type {InterceptorFulfilled, InterceptorItem, InterceptorManager, InterceptorRejected} from './types'


/**
 * 拦截器管理器实现类
 */
export class InterceptorManagerImpl<T> implements InterceptorManager<T> {
    /** 拦截器存储 */
    private handlers: Array<InterceptorItem<T> | null> = []

    /**
     * 使用拦截器
     * @param fulfilled 成功回调
     * @param rejected 失败回调
     * @returns 拦截器ID
     */
    use(fulfilled?: InterceptorFulfilled<T>, rejected?: InterceptorRejected): number {
        this.handlers.push({
            fulfilled,
            rejected
        })
        return this.handlers.length - 1
    }

    /**
     * 移除拦截器
     * @param id 拦截器ID
     */
    eject(id: number): void {
        if (this.handlers[id]) {
            this.handlers[id] = null
        }
    }

    /**
     * 清空所有拦截器
     */
    clear(): void {
        this.handlers = []
    }

    /**
     * 遍历拦截器
     * @param fn 遍历函数
     */
    forEach(fn: (interceptor: InterceptorItem<T>) => void): void {
        this.handlers.forEach((interceptor) => {
            if (interceptor !== null) {
                fn(interceptor)
            }
        })
    }
} 